package cn.com.xy.sms.sdk.service.number;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.com.xy.sms.sdk.Iservice.XyCallBack;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.entity.NumberInfo;
import cn.com.xy.sms.sdk.db.entity.NumberInfoManager;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetUtil;
import cn.com.xy.sms.sdk.util.CallBackState;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XyUtil;
import cn.com.xy.sms.util.SdkCallBack;

/* SDK-428 huangzhiqiang 20160615 start */
public class UploadUserTagService {
    public static final String TAG_NUM_KEY = "phonenum"; // 用户标记上传报文中的号码key
    public static final String TAG_TYPE_KEY = "tagType"; // 用户标记上传报文中的用户标记类型key(1:系统预制类型 2:自定义类型)
    public static final String TAG_CONTENT_KEY = "content"; // 用户标记上传报文中的用户标记内容key

    /**
     * 上传用户标记到服务器
     * 
     * @param uploadNumMap 需要上传的号码对应用户标记及标记类型Map
     * @param extend 扩展参数
     * @param callBack 
     *            index0(状态):
     *                 CallBackState.UPLOAD_COMPLETE:当前线程或新线程，上传完成
     *                 CallBackState.ERROR:当前线程或新线程，存在异常，上传失败
     *            index1:Set<String>类型 号码集合(可能为null)
     *            index2:
     *                 (index0 == CallBackState.UPLOAD_COMPLETE):JSONArray类型 上传成功的号码集合,例:
     *                      ["13826665653","13854629387"]
     *                 (index0 == CallBackState.ERROR):String类型 异常信息
     */
    public static void uploadToService(Map<String, String[]> uploadNumMap, Map<String, String> extend,
            final XyCallBack callBack) {
        if (uploadNumMap == null || uploadNumMap.isEmpty()) {
            XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, null, "no number");
            return;
        }

        final Set<String> uploadNums = uploadNumMap == null ? null : uploadNumMap.keySet();
        final String reqeustContent = createReqeustContent(uploadNumMap, extend);
        if (StringUtils.isNull(reqeustContent)) {
            XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, uploadNums, "reqeustContent == null");
            return;
        }

        SdkCallBack netSdkCallBack = new SdkCallBack() {

            @Override
            public void execute(Object... obj) {
                try {
                    int callBackState = (Integer) obj[0];
                    Object result = obj[1];
                    if (callBackState != CallBackState.REQUEST_SUCCESS) {
                        XyUtil.doXycallBackResult(callBack, callBackState, uploadNums, result);
                        return;
                    }

                    JSONArray uploadSuccessNums = updateUploadUserTagStatusAndReturnUploadSuccessNums(result);
                    XyUtil.doXycallBackResult(callBack, CallBackState.UPLOAD_COMPLETE, uploadNums, uploadSuccessNums);
                } catch (Throwable e) {
                    LogManager.e(Constant.TAG, "UploadUserTagService uploadToService execute error:",
                            e);
                    XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, uploadNums, e.getMessage());
                }
            }
        };
        try {
            NetUtil.executeServiceHttpRequest(NetUtil.REQ_NUM_MARK, reqeustContent, extend, netSdkCallBack);
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "UploadUserTagService uploadToService error:", e);
            XyUtil.doXycallBackResult(callBack, CallBackState.ERROR, uploadNums, e.getMessage());
        }
    }

    /**
     * 用户标记上传请求参数
     * 
     * @param uploadNumMap 号码对应用户标记及标记类型Map
     * @param extend 扩展参数
     * @return 例: [ {"phonenum":"13826665653","tagType":0,"content":"房产中介"},
     *         {"phonenum":"13854629387","tagType":1,"content":"自定义标记"} ]
     */
    private static String createReqeustContent(Map<String, String[]> uploadNumMap, Map<String, String> extend) {
        if (uploadNumMap == null || uploadNumMap.isEmpty()) {
            return null;
        }
        JSONArray reqeustJsonArray = new JSONArray();
        try {
            Set<Entry<String, String[]>> entrySet = uploadNumMap.entrySet();
            for (Entry<String, String[]> entry : entrySet) {
                String num = entry.getKey();
                if (StringUtils.isNull(num)) {
                    continue;
                }

                String[] uploadInfoArr = entry.getValue();
                if (uploadInfoArr == null || uploadInfoArr.length < 2) {
                    continue;
                }
                JSONObject numInfoObj = new JSONObject();
                String tag = uploadInfoArr[0];
                String tagType = uploadInfoArr[1];
                numInfoObj.put(TAG_CONTENT_KEY, tag);
                numInfoObj.put(TAG_TYPE_KEY, tagType);
                numInfoObj.put(TAG_NUM_KEY, num);
                reqeustJsonArray.put(numInfoObj);

            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "UploadUserTagService createReqeustContent error:", e);
        }
        return reqeustJsonArray.length() == 0 ? null : reqeustJsonArray.toString();
    }

    private static JSONArray updateUploadUserTagStatusAndReturnUploadSuccessNums(Object resultObj) throws Exception {
        JSONObject resultJson = new JSONObject((String) resultObj);
        boolean uploadUserTagSuccess = "200".equals(resultJson.optString("status"));
        if (!uploadUserTagSuccess) {
            return null;
        }

        JSONArray uploadSuccessNums = resultJson.optJSONArray("items");
        if (uploadSuccessNums == null) {
            return null;
        }

        int length = uploadSuccessNums.length();
        for (int i = 0; i < length; i++) {
            String num = uploadSuccessNums.getString(i);
            // 更新上传状态为1，代表已上传用户标记；手机用户上传标记数量及几率都很小，直接在循环中操作数据库，暂不考虑性能问题
            NumberInfoManager.updateUploadUserTagStatus(num, NumberInfo.UPLOAD_STATUS_UPLOADED);
        }
        return uploadSuccessNums;
    }
}
/* SDK-428 huangzhiqiang 20160615 end */
